<script setup lang="ts">
import { computed, ref, StyleValue } from 'vue'
import { useRouter } from 'vue-router';
import { showToast, Loading } from 'vant';
import { useUserStore } from '@/stores/user';

import { fetchWithdrawalOptions } from '@/api/withdraw'
import { fetchUserAccountInfo } from '@/api/user';

import BiPopup from '@/components/bi-popup/index.vue'
import BiNavBar from '@/components/bi-navbar/index.vue'

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref<UserInfo>(userStore.info)

const loading = ref(true)
const handleStopLoading = () => {
    loading.value = false
}
const userAccount = ref<any>({})
const handleFetchAccountInfo = async () => {
    try {
        const res = await fetchUserAccountInfo({ device: userStore.device })
        userAccount.value = res.data.data

        handleStopLoading()
    } catch (error) {
        throw new Error(error as string)
    }
}
handleFetchAccountInfo()

interface TargetAmount {
    chalices: number,
    amount: number,
    availableNewbie: number,
    flames: number
}
const withdrawOptions = ref([] as TargetAmount[])
const handleFetchWithdrawalOptions = async () => {
    try {
        const hideOneDollarOption = userInfo.value.finishNewbieWithdraw === 0 // 0 隐藏金额为1的选项，1 显示金额为1的选项
        const userFinishWithdraw = userInfo.value.finishNewbieTask === 1 // 0 未完成新手提现，1 进行过新手提现
        const res = await fetchWithdrawalOptions({ device: userStore.device })
        withdrawOptions.value = res.data.data.filter((item: { availableNewbie: number; }) => {
            return (hideOneDollarOption || userFinishWithdraw) ? item.availableNewbie === 0 : true
        })
    } catch (error) {
        throw new Error(error as string)
    }
}
handleFetchWithdrawalOptions()
const targetAmount = computed<TargetAmount>(() => {
    const target = withdrawOptions.value.find(item => {
        return userInfo.value.totalAmount <= item.amount
    })
    return target || { chalices: 0, amount: 0 } as TargetAmount
})
const bannerPorgressWidth = computed(() => {
    const rate = Math.round((userInfo.value.totalAmount / targetAmount.value.amount) * 100)
    return Number.isFinite(rate) ? rate : 0
})

const useProgressStyle = (chalices: number): StyleValue => {
    const result = Math.round((userInfo.value.totalAmount / chalices) * 100)
    return { '--item-progress-width': `${result}%` }
}
const useCardText = (amount: number): string => {
    return userInfo.value.chalicePoints < amount ? `${amount} Funds` : 'Exchange'
}

const handleToInput = (amount: TargetAmount) => {
    if (userInfo.value.isCompleteNewTail == 0 && amount.availableNewbie == 1) {
        showToast('Newbie task unfinished')
        return
    }

    if (amount.amount > userInfo.value.totalAmount) {
        openPopup('Funds not enough', 'Funds')
        return
    }

    const query = {
        amount: amount.amount
    }
    router.push({ path: '/input', query })
}

const showPopup = ref(false)
const popupTips = ref('')
const popupMaterials = ref('')
const openPopup = (tips: string, Materials: string): void => {
    popupTips.value = tips
    popupMaterials.value = Materials
    showPopup.value = true
}
const handleToGetChalice = () => {
    const hasTurntableNums = userInfo.value.turntableNums < userInfo.value.turntableTotalNums
    const hasLotteryNums = userInfo.value.lotteryNums < userInfo.value.lotteryTotalNums

    if (hasTurntableNums) {
        router.push('/egg')
        return
    }

    if (hasLotteryNums) {
        router.push('/turntable')
        return
    }

    if (!hasTurntableNums && !hasLotteryNums) {
        router.push('/gameCenter')
        return
    }
}

</script>

<template>
    <BiNavBar title="Get travel funds" @click-left="router.back">
        <template v-slot:right>
            <RouterLink :to="{ path: '/flow' }">
                <div class="to-flow">
                    <img class="to-flow_icon" src="@/assets/imgs/exchange/flow.png" alt="toFlowIcon" width="40">
                </div>
            </RouterLink>
        </template>
    </BiNavBar>

    <div class="progress">
        <h1 class="progress-title">Next Payout for ${{ targetAmount.amount.toFixed(2) }}</h1>
        <div class="progress-bar">
            <div class="progress-bar-info" :style="{ '--progress-width': `${bannerPorgressWidth}%` }">
                <svg height="100%">
                    <text ref="text" class="progress-bar-info_text" text-anchor="middle" x="50%" y="67%">{{
        userInfo.totalAmount }} / {{ targetAmount.amount }} Funds</text>
                </svg>
                <img class="progress-bar-info_img" src="@/assets/imgs/doller.png" alt="chalices" width="18">
            </div>
        </div>
    </div>

    <main class="main">
        <div class="withdraw">
            <Loading v-if="loading" style="position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);" vertical
                color="#6b61ad" text-color="#6b61ad">
                Loading...
            </Loading>
            <ul v-else class="withdraw-grid">
                <li class="withdraw-card" v-for="item in withdrawOptions">
                    <div class="withdraw-card-container" @click="handleToInput(item)">
                        <span class="withdraw-card-container_span">${{ item.amount.toFixed(2) }}</span>
                        <img src="@/assets/imgs/exchange/logo_big.png" alt="paypal" width="100"
                            class="withdraw-card-container_img">
                        <div class="withdraw-card-container_btn" :style="useProgressStyle(item.amount)">
                            <span>{{ useCardText(item.amount) }}</span>
                            <template>
                                {{ item.amount }} Funds
                            </template>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </main>

    <!-- 提醒用户获取圣杯或火焰的弹窗 -->
    <BiPopup v-model:show="showPopup" :button-text="`Get ${popupMaterials}`" type="task" @click="handleToGetChalice">
        <span class="red-text"
            style="width: 58vmin;margin-top: 0;line-height: 1.5;font-weight: bold;text-align: center;">
            {{ popupTips }}</span>
    </BiPopup>

</template>

<style scoped lang="scss">
@import url(./exchange.scss);
</style>